package com.cloudeasy.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.SnowFlake;
import com.cloudeasy.user.dto.RoleDTO;
import com.cloudeasy.user.mapper.RoleMapper;
import com.cloudeasy.user.po.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    private final SnowFlake snowFlake;

    public RoleService(SnowFlake snowFlake) {
        this.snowFlake = snowFlake;
    }

    /**
     * 根据名称查询角色
     *
     * @param name 角色名称
     * @return {@link Role}
     */
    public Role getByName(String name) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return this.getOne(queryWrapper);
    }

    /**
     * 获取角色信息
     *
     * @param ids 角色Id列表
     * @return {@link List<Role>}
     */
    public List<Role> list(List<String> ids) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        return this.list(queryWrapper);
    }

    /**
     * 添加角色
     *
     * @param roleDTO {@link RoleDTO}
     * @return {@link Boolean}
     */
    public Boolean save(RoleDTO roleDTO) {
        if (this.getByName(roleDTO.getName()) != null) {
            throw new CloudEasyException(ResultCodeEnum.NAME_EXISTS);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleDTO, role);
        role.setId(String.valueOf(snowFlake.nextId()));
        return this.save(role);
    }

    /**
     * 更新角色信息
     *
     * @param roleId  角色Id
     * @param roleDTO {@link RoleDTO}
     * @return {@link Boolean}
     */
    public Boolean update(String roleId, RoleDTO roleDTO) {
        Role role = this.getById(roleId);
        if (role == null) {
            throw new CloudEasyException(ResultCodeEnum.ID_NOT_EXISTS);
        }
        if (!role.getName().equals(roleDTO.getName())&&this.getByName(roleDTO.getName()) != null) {
            throw new CloudEasyException(ResultCodeEnum.NAME_EXISTS);
        }
        BeanUtils.copyProperties(roleDTO, role);
        return this.updateById(role);
    }

    /**
     * 获取角色Id列表中可用角色
     *
     * @param roleIds 角色Id列表
     * @param enable  可用状态
     * @return {@link List<Role>}
     */
    public List<Role> listByRoleIdsAndEnable(List<String> roleIds, boolean enable) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", roleIds)
                .eq("enable", enable);
        return this.list(queryWrapper);
    }
}
